/**
 * 文本分析工具 - IntelliMark适配版
 * 提供专业的Markdown文本分析功能
 */

import { BaseTool, ToolResult, AnalysisType, AnalysisOptions } from "../../types/tools";
import { getEnhancedAIProviderManager } from "../../utils/aiProviderAdapter";
import { formatPrompt } from "../../utils/promptTemplates";
import { HumanMessage, SystemMessage } from "@langchain/core/messages";
import { v4 as uuidv4 } from 'uuid';

// 文本分析结果接口
export interface TextAnalysisResult {
  summary: string;
  score: number;
  details: Record<string, any>;
  suggestions: string[];
  metrics?: Record<string, number>;
}

// 文本分析配置
export interface TextAnalysisConfig {
  defaultProvider: string;
  maxTokens: number;
  temperature: number;
  enableCache: boolean;
  cacheTimeout: number;
}

export class TextAnalysisTool extends BaseTool {
  private config: TextAnalysisConfig;
  private cache: Map<string, { result: TextAnalysisResult; timestamp: number }> = new Map();

  constructor(config: Partial<TextAnalysisConfig> = {}) {
    super();

    this.name = 'text-analysis';
    this.description = '专业的IntelliMark文本分析工具，支持风格分析、可读性分析、结构分析、情感分析等多种Markdown文本分析功能';
    this.category = 'textAnalysis';
    this.enabled = true;
    this.requiresAuth = false;

    this.config = {
      defaultProvider: 'openai-gpt4',
      maxTokens: 4000,
      temperature: 0.3, // 分析任务需要较低的温度以保证一致性
      enableCache: true,
      cacheTimeout: 3600,
      ...config,
    };

    this.parameters = [
      {
        name: 'text',
        type: 'string' as const,
        description: '要分析的Markdown文本内容',
        required: true,
      },
      {
        name: 'analysisType',
        type: 'string' as const,
        description: '分析类型',
        required: true,
        validation: {
          enum: ['sentiment', 'readability', 'style', 'structure', 'grammar', 'seo', 'keywords', 'summarization'],
        },
      },
      {
        name: 'options',
        type: 'object' as const,
        description: '分析选项',
        required: false,
      },
    ];
  }

  async execute(input: any): Promise<ToolResult> {
    const startTime = Date.now();
    const requestId = uuidv4();

    try {
      // 验证输入参数
      const validatedInput = this.validateInput(input);

      // 生成缓存键
      const cacheKey = this.generateCacheKey(validatedInput);

      // 检查缓存
      if (this.config.enableCache) {
        const cachedResult = this.getCachedResult(cacheKey);
        if (cachedResult) {
          return {
            success: true,
            data: cachedResult,
            metadata: {
              cacheHit: true,
              executionTime: Date.now() - startTime,
              requestId,
            },
          };
        }
      }

      // 执行文本分析
      const result = await this.performAnalysis(validatedInput);

      // 缓存结果
      if (this.config.enableCache) {
        this.cacheResult(cacheKey, result);
      }

      const executionTime = Date.now() - startTime;

      return {
        success: true,
        data: result,
        metadata: {
          executionTime,
          analysisType: validatedInput.analysisType,
          model: this.config.defaultProvider,
          cacheHit: false,
          requestId,
          inputLength: validatedInput.text.length,
        },
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);

      return {
        success: false,
        error: errorMessage,
        metadata: {
          executionTime: Date.now() - startTime,
          requestId,
        },
      };
    }
  }

  private validateInput(input: any): { text: string; analysisType: AnalysisType; options?: AnalysisOptions } {
    if (!input.text || typeof input.text !== 'string') {
      throw new Error('text参数是必需的且必须是字符串');
    }

    if (!input.analysisType) {
      throw new Error('analysisType参数是必需的');
    }

    const validTypes: AnalysisType[] = ['sentiment', 'readability', 'style', 'structure', 'grammar', 'seo', 'keywords', 'summarization'];
    if (!validTypes.includes(input.analysisType)) {
      throw new Error(`无效的analysisType: ${input.analysisType}`);
    }

    const validated: any = {
      text: input.text,
      analysisType: input.analysisType,
    };

    if (input.options) {
      validated.options = {
        detailLevel: input.options.detailLevel || 'detailed',
        includeSuggestions: input.options.includeSuggestions !== false,
        targetAudience: input.options.targetAudience || 'general',
        language: input.options.language || 'zh-CN',
        ...input.options,
      };
    }

    return validated;
  }

  private async performAnalysis(params: { text: string; analysisType: AnalysisType; options?: AnalysisOptions }): Promise<TextAnalysisResult> {
    const providerManager = getEnhancedAIProviderManager();

    // 构建系统提示词
    const systemPrompt = this.buildSystemPrompt(params.analysisType);

    // 构建用户提示词
    const userPrompt = this.buildUserPrompt(params);

    // 构建消息
    const messages = [
      new SystemMessage(systemPrompt),
      new HumanMessage(userPrompt)
    ];

    // 调用AI服务
    const response = await providerManager.generateEnhancedResponse(
      messages,
      this.config.defaultProvider,
      {
        temperature: this.config.temperature,
        maxTokens: this.config.maxTokens,
      }
    );

    // 解析分析结果
    return this.parseAnalysisResult(response.content, params.analysisType);
  }

  private buildSystemPrompt(analysisType: AnalysisType): string {
    const basePrompt = '你是一位专业的文本分析专家，擅长深入分析Markdown文本的各个方面。';

    switch (analysisType) {
      case 'sentiment':
        return basePrompt + '你专注于分析文本的情感倾向、情感强度和情感变化。';

      case 'readability':
        return basePrompt + '你专注于评估文本的可读性、阅读难度和理解门槛。';

      case 'style':
        return basePrompt + '你专注于分析文本的写作风格、语言特征和表达方式。';

      case 'structure':
        return basePrompt + '你专注于分析文本的结构组织、逻辑流程和层次关系。';

      case 'grammar':
        return basePrompt + '你专注于检查文本的语法正确性、用词准确性和表达规范性。';

      case 'seo':
        return basePrompt + '你专注于分析文本的SEO优化程度、关键词密度和搜索引擎友好度。';

      case 'keywords':
        return basePrompt + '你专注于提取文本的核心关键词、主题概念和专业术语。';

      case 'summarization':
        return basePrompt + '你专注于生成文本的准确摘要，突出核心观点和关键信息。';

      default:
        return basePrompt;
    }
  }

  private buildUserPrompt(params: { text: string; analysisType: AnalysisType; options?: AnalysisOptions }): string {
    const { text, analysisType, options } = params;

    let prompt = `请对以下Markdown文本进行${this.getAnalysisTypeName(analysisType)}分析：\n\n\`\`\`markdown\n${text}\n\`\`\`\n\n`;

    // 添加分析要求
    prompt += '## 分析要求\n';
    prompt += '- 提供详细的分析报告\n';
    prompt += '- 给出具体的评分（1-10分）\n';
    prompt += '- 列出发现的问题和改进建议\n';

    if (options?.includeSuggestions) {
      prompt += '- 提供实用的改进建议\n';
    }

    switch (analysisType) {
      case 'sentiment':
        prompt += '- 识别主要情感（积极/消极/中性）\n';
        prompt += '- 分析情感强度（1-10）\n';
        prompt += '- 检测情感变化\n';
        break;

      case 'readability':
        prompt += '- 计算阅读难度等级\n';
        prompt += '- 分析句子复杂度\n';
        prompt += '- 评估词汇难度\n';
        prompt += '- 提供可读性评分\n';
        break;

      case 'style':
        prompt += '- 识别写作风格类型\n';
        prompt += '- 分析语言特征\n';
        prompt += '- 评估语体语调\n';
        prompt += '- 检查修辞手法\n';
        break;

      case 'structure':
        prompt += '- 分析文档结构\n';
        prompt += '- 检查逻辑流程\n';
        prompt += '- 评估层次关系\n';
        prompt += '- 识别结构问题\n';
        break;

      case 'grammar':
        prompt += '- 检查语法错误\n';
        prompt += '- 识别用词问题\n';
        prompt += '- 检查标点符号\n';
        prompt += '- 评估表达准确性\n';
        break;

      case 'seo':
        prompt += '- 分析关键词密度\n';
        prompt += '- 检查标题优化\n';
        prompt += '- 评估内容质量\n';
        prompt += '- 提供SEO建议\n';
        break;

      case 'keywords':
        prompt += '- 提取核心关键词\n';
        prompt += '- 识别主题概念\n';
        prompt += '- 分析关键词权重\n';
        prompt += '- 提供关键词建议\n';
        break;

      case 'summarization':
        prompt += '- 生成准确摘要\n';
        prompt += '- 突出核心观点\n';
        prompt += '- 保持关键信息\n';
        prompt += '- 控制摘要长度\n';
        break;
    }

    if (options?.targetAudience) {
      prompt += `\n## 目标读者\n${options.targetAudience}\n`;
    }

    if (options?.detailLevel) {
      prompt += `\n## 分析深度\n${options.detailLevel}\n`;
    }

    prompt += '\n请以结构化的JSON格式返回分析结果，包含以下字段：\n';
    prompt += '- summary: 分析总结\n';
    prompt += '- score: 总体评分（1-10）\n';
    prompt += '- details: 详细分析数据\n';
    prompt += '- suggestions: 改进建议列表\n';
    prompt += '- metrics: 相关指标数据（可选）';

    return prompt;
  }

  private parseAnalysisResult(content: string, analysisType: AnalysisType): TextAnalysisResult {
    try {
      // 尝试解析JSON格式的结果
      const jsonMatch = content.match(/```json\s*\n([\s\S]*?)\n```/);
      if (jsonMatch) {
        return JSON.parse(jsonMatch[1]);
      }

      // 尝试直接解析JSON
      if (content.trim().startsWith('{') && content.trim().endsWith('}')) {
        return JSON.parse(content);
      }

      // 如果无法解析JSON，则从文本中提取信息
      return this.parseTextAnalysisResult(content, analysisType);

    } catch (error) {
      console.warn('Failed to parse analysis result as JSON, falling back to text parsing:', error);
      return this.parseTextAnalysisResult(content, analysisType);
    }
  }

  private parseTextAnalysisResult(content: string, analysisType: AnalysisType): TextAnalysisResult {
    // 从文本中提取分析结果的基础实现
    return {
      summary: content.substring(0, Math.min(500, content.length)) + '...',
      score: 7, // 默认评分
      details: {
        analysisType,
        fullText: content,
      },
      suggestions: ['请参考完整分析结果获取详细建议'],
    };
  }

  private getAnalysisTypeName(analysisType: AnalysisType): string {
    const nameMap = {
      sentiment: '情感',
      readability: '可读性',
      style: '风格',
      structure: '结构',
      grammar: '语法',
      seo: 'SEO优化',
      keywords: '关键词',
      summarization: '摘要',
    };
    return nameMap[analysisType] || analysisType;
  }

  private generateCacheKey(params: { text: string; analysisType: AnalysisType; options?: AnalysisOptions }): string {
    const keyData = {
      text: params.text,
      analysisType: params.analysisType,
      options: params.options,
    };
    return Buffer.from(JSON.stringify(keyData)).toString('base64');
  }

  private getCachedResult(cacheKey: string): TextAnalysisResult | null {
    const cached = this.cache.get(cacheKey);
    if (!cached) {
      return null;
    }

    const now = Date.now();
    if (now - cached.timestamp > this.config.cacheTimeout * 1000) {
      this.cache.delete(cacheKey);
      return null;
    }

    return cached.result;
  }

  private cacheResult(cacheKey: string, result: TextAnalysisResult): void {
    this.cache.set(cacheKey, {
      result,
      timestamp: Date.now(),
    });

    // 清理过期缓存
    this.cleanExpiredCache();
  }

  private cleanExpiredCache(): void {
    const now = Date.now();
    const expiredKeys: string[] = [];

    this.cache.forEach((cached, key) => {
      if (now - cached.timestamp > this.config.cacheTimeout * 1000) {
        expiredKeys.push(key);
      }
    });

    expiredKeys.forEach(key => this.cache.delete(key));
  }

  // 公共方法
  public clearCache(): void {
    this.cache.clear();
  }

  public getCacheSize(): number {
    return this.cache.size;
  }

  public updateConfig(newConfig: Partial<TextAnalysisConfig>): void {
    this.config = { ...this.config, ...newConfig };
  }

  // 便捷分析方法
  public async analyzeStyle(text: string, options?: AnalysisOptions): Promise<TextAnalysisResult> {
    return this.execute({ text, analysisType: 'style', options }).then(result => result.data as TextAnalysisResult);
  }

  public async analyzeReadability(text: string, options?: AnalysisOptions): Promise<TextAnalysisResult> {
    return this.execute({ text, analysisType: 'readability', options }).then(result => result.data as TextAnalysisResult);
  }

  public async analyzeStructure(text: string, options?: AnalysisOptions): Promise<TextAnalysisResult> {
    return this.execute({ text, analysisType: 'structure', options }).then(result => result.data as TextAnalysisResult);
  }

  public async extractKeywords(text: string, options?: AnalysisOptions): Promise<TextAnalysisResult> {
    return this.execute({ text, analysisType: 'keywords', options }).then(result => result.data as TextAnalysisResult);
  }

  public async analyzeSEO(text: string, options?: AnalysisOptions): Promise<TextAnalysisResult> {
    return this.execute({ text, analysisType: 'seo', options }).then(result => result.data as TextAnalysisResult);
  }
}

// 导出便捷函数
export const createTextAnalysisTool = (config?: Partial<TextAnalysisConfig>): TextAnalysisTool => {
  return new TextAnalysisTool(config);
};

// 默认实例
export const defaultTextAnalysisTool = new TextAnalysisTool();